package com.lifq.tmp;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: LiFuqiang
 * @Date: 2023/4/20 10:48
 * @Version 1.0
 * @description
 */
public class TRemp {
    private static String appkey = "8483ef6fbcf717006592d9f2b71e1e0c";
    private static String secret = "e6278a359c2dc9ec776a95404494ffaf";

    public static void main(String[] args) throws Exception{
        ApiRequestDemo apiRequestDemo = new ApiRequestDemo();
        Long timestamp = System.currentTimeMillis();
        Map<String, List<String>> queryParams = new HashMap<>();
        //queryParams.put("pageNo", Arrays.asList("1"));
        //queryParams.put("pageSize", Arrays.asList("1"));
        queryParams.put("sex", Arrays.asList("1"));
        String sign = apiRequestDemo.sign(queryParams, timestamp);

        System.out.println(sign);
        System.out.println(timestamp);
    }

    public static String sign(Map<String, List<String>> queryParams, Long timestamp) {
        StringBuilder signStr = new StringBuilder(appkey).append(timestamp);

        TreeMap<String, List<String>> sortParams = new TreeMap<>(queryParams);
        for (String key : sortParams.keySet()) {
            List<String> values = sortParams.get(key);
            if (values == null) {
                //空参数不参与校验
                continue;
            }
            String valueStr = values.stream().sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.joining(","));
            if ("".equals(valueStr.trim())) {
                //空参数不参与校验
                continue;
            }
            signStr.append("&").append(key).append("=").append(valueStr);
        }

        String sign = sign(signStr.toString());
        return sign;
    }


    public static String sign(String signStr) {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("utf-8"), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(signStr.getBytes("utf-8"));
        } catch (Exception gse) {
            throw new RuntimeException(gse);
        }
        return byte2hex(bytes);
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                str.append("0");
            }
            str.append(hex.toUpperCase());
        }
        return str.toString();
    }
}
